How To Install, Use And Write A Userscript: A Tampermonkey & Violentmonkey Tutorial
Introduction
Have you ever wondered if you could load the next page when you reach the end of a web page ? Or maybe add quick links and information from external pages (ex: add the Rotten Tomatoes score and link to the IMDb page of a movie) ?
Userscripts can answer all this questions.
A userscript is a set of JavaScript code and metadata that is executed when a web page is loading:
- The code is a sequence of instructions that tells the browser how to modify the page.
- The metadata are information about the userscript, for example: the web pages where they should run, the resources and libraries they require, and more.
In order to add, update and manage userscripts, a userscript manager must be installed.
Technically, a userscript is just a text file that ends with .user.js
. This fact allows userscript managers to detect and install userscripts when a file is opened in the browser.
Installing a userscript manager
From my experience, Tampermonkey is best suited for Chromium-based browsers such as Google Chrome and Opera.
Violentmonkey is currently the best supported userscript manager for Firefox.
Tampermonkey
With more than 10 million users, Tampermonkey is the leading userscript manager. It's also available in all the major navigators.
Here are the direct pages where you can install the Tampermonkey extension:
- Google Chrome: https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=en
- Opera: https://addons.opera.com/en/extensions/details/tampermonkey-beta/
- Microsoft Edge: https://microsoftedge.microsoft.com/addons/detail/tampermonkey/iikmkjmpaadaobahmlepeloendndfphd
- Safari: https://apps.apple.com/app/apple-store/id1482490089?mt=8
More detailed instructions to install Tampermonkey and a comprehensive features overview is presented in the following links: Google Chrome, Opera, Microsoft Edge, Safari.
Violentmonkey
Violentmonkey is the main alternative to Tampermonkey, and is completely open source. It's available in Firefox, Chrome, Opera and Maxthon.
The following page lists the download links for the different supported browsers: https://violentmonkey.github.io/get-it/
Greasemonkey
Greasemonkey is the original userscript manager. Following Firefox 57, and starting from the version Greasemonkey 4, the extension changed its API to be compatible with the Browser Extension API, and no longer support scripts written using the older GM_
synchronous API (more explanations can be found in this blog post).
I discourage using it at the moment because the majority of userscripts are written using the older API and the other userscript managers don't support the new asynchronous API.
You will have to install it only if a userscript you want to add is written specifically using the new GM.
asynchronous API and doesn't have a polyfill to support the older API (very rarely).
Searching for userscripts
The majority of userscripts are hosted either on openuserjs.org or greasyfork.org.
OpenUserJS
The following example illustrates how to search for a userscript on OpenUserJS and install it on Google Chrome with Tampermonkey:
- Navigate to the home page
- Enter the keywords into the
Search Userscripts
text input: can be the target website name, the desired feature, etc. For example, let's search for a Google userscript - Open the script page you want to install, for example
Endless Google
- If the script's description is corresponding to the features you are searching for, install the script by clicking the
Install
button - Confirm the installation by clicking
Install
- The userscript can now be tested by opening or reloading the target website
GreasyFork
Firefox with Violentmonkey is used in the next steps:
- Navigate to the Scripts page
- Enter the keywords into the
Search scripts
text input: can be the target website name, the desired feature, etc. For example, let's search for a Feedly userscript - Open the script page you want to install, for example
Feedly filtering and sorting
- If the script's description is corresponding to the features you are searching for, install the script by clicking the
Install this script
button - Confirm the installation
- The userscript can now be tested by opening or reloading the target website
Alternatives
Userscripts.org used to be the leading userscript repository. But the website was shut down in 2014, and a mirror web page was launched to host all it's original userscripts: userscripts-mirror.org
There are some userscripts that are hosted on personal or github pages, a general search engine such as Google can be used in this case to search for them.
Using userscripts
A userscript can be configured and interacted with in different ways after installing it:
- Some userscripts will indicate in their description or documentation page that they will add a button to a specific part of the page to open a settings menu or execute another action
- They can also register commands and/or shortcuts in the userscript manager to open the setting menu or to execute another action on the current page
- Others won't need any configuration and will work as is
The userscript manager can also be used to configure security, storage and other script specific settings such as the pages where the script should run as presented in the following section.
Includes and Excludes
The includes/matches are the web pages where the script will run (@include supports regular expressions and @match is safer). The excludes are the pages where the script shouldn't run.
Even though the userscript already defines includes and excludes in its metadata, they can be overwritten using the userscript manager.
Tampermonkey
- Open the Dashboard by clicking on the Tampermonkey button and selecting
Dashboard
- Click on the userscript you want to configure
- Switch to the
Settings
tab. You can now add additional includes, matches and excludes. You can also disable the original includes and excludes
Violentmonkey
- Open the Dashboard by clicking on the Violentmonkey button and selecting
Open Dashboard
- Click on the edit button next to the userscript you want to configure
- Switch to the
Settings
tab. You can now add additional includes, matches and excludes. You can also disable the original includes and excludes
Writing your own userscripts
Prerequisites
Basic HTML knowledge is required. Get started with HTML.
Basic CSS knowledge is also needed, especially selectors. Get introduced to CSS selectors.
If you are unfamiliar with JavaScript, I recommend reading the following first steps guides.
If you were already introduced to JavaScript and need a refresher, or you just need a summarized tutorial to quickly learn the language, here is a re-introduction to JavaScript
You can also follow the chapters of this intermediary JavaScript guide, and read this exhaustive JavaScript reference.
Your first userscript
As mentioned earlier, a userscript is a set of JavaScript code and metadata which are technically just JavaScript comments.
From the userscript manager dashboard, click on the +
button to create a new userscript.
Change the name, description and the match pattern to target a specific web page. Replace // Your code here...
with alert('Hello World !');
Now navigate to your target website or refresh it if it's already open. You should have an alert pop up that displays Hello World
That's it!
You can now start experimenting with the GM_*
API to store data for example, or add third-party code libraries (such as JQuery) to help you write less or to reuse existing code.
Using the API and adding external libraries
If you want to use the GM_*
API, you must declare a @grant
header in the metadata followed by the API function name (such as GM_getValue
, GM_setValue
, etc.)
// @grant GM_setValue
// @grant GM_getValue
A userscript documentation describing the available headers (metadata) and the API (GM_*
) can be found in the following page. An alternative metadata documentation can be found here.
Third-party libraries can be added by defining the @require
header followed by the library URL. For example:
// @require https://code.jquery.com/jquery-3.2.1.min.js
Userscript idioms and code snippets
- Query and remove a page element:
document.querySelector("#element_id").remove();
- Store an object:
GM_setValue("MY_OBJECT_KEY", JSON.stringify(myObject));
- Retrieve an object:
var myObject = JSON.parse(GM_getValue("MY_OBJECT_KEY", "{}"));
- Replace the current URL and redirect the page:
var link = document.URL.replace("domain.fr", "domain.com"); window.location.href=link;
- Add a button to execute some function on the page:
var btn = document.createElement("button"); btn.innerHTML = "My button"; btn.onclick = () => { alert("My button clicked !"); return false; }; document.querySelector("btn_predecessor_selector").after(btn);
- Append a style to the page:
var css = "h1 { background: red; }" var style = document.createElement("style"); style.type = "text/css"; style.appendChild(document.createTextNode(css)); document.head.appendChild(style);
- Fetching and parsing an external page:
fetch("http://example.com/path-name") .then(response => response.text()) .then(text => { var parser = new DOMParser(); var htmlDocument = parser.parseFromString(text, "text/html"); var content = htmlDocument.documentElement.querySelector("element_selector"); alert("My fetched element content: " + content.textContent); });
Soufiane Sakhi is an AWS Certified Solutions Architect – Associate and a professional full stack developer.